﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using MasterDetailTemplate.Models;
using SQLite;

namespace MasterDetailTemplate.Services.impl
{
    public class DietRecorderStorageService : IDietRecorderStorageService {
        public const string dbName = "dietRecorder.db";

        public static readonly string dbPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder
                .LocalApplicationData), dbName);

        private SQLiteAsyncConnection _connection;
        private IPreferenceStorage _preference;

        public SQLiteAsyncConnection Connection =>
            _connection ?? (_connection = new SQLiteAsyncConnection(dbPath));
        public async Task InitializeAsync() {
            await Connection.CreateTableAsync<DietRecorder>();
            _preference.Set(DietRecorderStorageConstants.VersionKey,DietRecorderStorageConstants.VERSION);
        }

        public bool IsInitialized() =>
            _preference.Get(DietRecorderStorageConstants.VersionKey,DietRecorderStorageConstants.DEFAULTVERSION)
                .Equals(DietRecorderStorageConstants.VERSION);

        public async Task<DietRecorder> GetDietRecorderAsync(int id) =>
            await Connection.Table<DietRecorder>()
                .FirstOrDefaultAsync(p => p.Id == id);

        public async Task Insert(DietRecorder dietRecorder) =>
            await Connection.InsertOrReplaceAsync(dietRecorder);

        public async Task InsertAll(List<DietRecorder> dietRecorders) =>
            await Connection.InsertAllAsync(dietRecorders);

        public async Task<List<DietRecorder>> GetDietRecordersAsync(
            Expression<Func<DietRecorder, bool>> @where, int skip, int take) =>
            await Connection.Table<DietRecorder>().Where(where).Skip(skip).Take(take)
                .ToListAsync();

        public async Task<List<DietRecorder>> GetAllDietRecorderAsync(
            Expression<Func<DietRecorder, bool>> @where) =>
            await Connection.Table<DietRecorder>().Where(where).ToListAsync();

        public DietRecorderStorageService(IPreferenceStorage preference) {
            _preference = preference;
        }
        public async Task CloseConnection()
        {
            await _connection.CloseAsync();
            _connection = null;
        }
    }
}
